 package com.example.userclient.custom

import android.content.Context
import android.graphics.*
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.AttributeSet
import android.util.Log
import android.widget.Toast
import androidx.appcompat.widget.AppCompatImageView
import com.example.userclient.Main.ClientInfoHolder
import com.example.userclient.remote.AppExecutors
import java.lang.Exception
import java.lang.ref.SoftReference
import java.net.HttpURLConnection
import java.net.URL

 class  CustomImageView : AppCompatImageView, CustomImageURL {

    constructor(context: Context) : super(context)
    constructor(context: Context, attributeSet: AttributeSet) : this(context, attributeSet, 0)
    constructor(context: Context, attributeSet: AttributeSet, defStyleAttr: Int) : super(
        context,
        attributeSet,
        defStyleAttr
    )

    private val GET_DATA_SUCCESS = 1
    private val NETWORK_ERROR = 2
    private val SERVER_ERROR = 3


    private var callBackHandler = Handler(Looper.getMainLooper()){
        when(it.what){
            GET_DATA_SUCCESS -> {
                val bitmap = it.obj as Bitmap
                setImageBitmap(bitmap)
//                avatar = bitmap
                Log.i("CustomImageView","setBitMap")
                return@Handler true
            }
            NETWORK_ERROR -> {
                Toast.makeText(getContext(), "网络连接失败", Toast.LENGTH_SHORT).show();
                Log.i("CustomImageView","NETWORK_ERROR")
                return@Handler true
            }
            SERVER_ERROR -> {
                Toast.makeText(getContext(), "网络连接失败", Toast.LENGTH_SHORT).show();
                Log.i("CustomImageView","SERVER_ERROR")
                return@Handler true
            }
            else -> {
                Toast.makeText(getContext(), "网络连接失败", Toast.LENGTH_SHORT).show();
                Log.i("CustomImageView","else")
                return@Handler true
            }
        }

    }
//     private val AVATAR_SIZE = 120f //图片的大小
//     private val RADIUS = AVATAR_SIZE / 2 //裁剪圆形的半径
//
//     private val paint = Paint()
//
//     private val circlePath = Path()//圆形的路径
//
//     private var avatar:Bitmap? = null

//     override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
//         /**
//          * 在圆心 x:View宽度的一半 y:View高度的一半 半径为图片尺寸的一半 的位置上画圆
//          */
//         circlePath.addCircle(40f, height / 2f, RADIUS, Path.Direction.CW)
//     }
//
//
//
//     override fun onDraw(canvas: Canvas) {
//         super.onDraw(canvas)
//         //ktx的扩展方法,会自动保存恢复Canvas
//         Log.i("CustomImageView", "OnDraw")
////         canvas.withSave {
////             //重置画笔
////             paint.reset()
////             //利用Canvas来裁切去要画的范围,也就是那个圆形
////             canvas.clipPath(circlePath)
////             //在裁切后画上声明的Bitmap
////             canvas.drawBitmap(avatar!!, width / 2 - RADIUS, height / 2 - RADIUS, paint)
////         }
//     }


     override fun setImageURL(path: String?) {
        Log.i("CustomImageView", "path：$path")
        //开启一个线程用于联网
        if (!path.isNullOrEmpty()){
            Log.i("CustomImageView","size:${ClientInfoHolder.map.size}")
            if( ClientInfoHolder.map[path]?.get()!=null){
                val bitmap = ClientInfoHolder.map[path]?.get()
                //利用Message把图片发给Handler
                val msg = Message.obtain()
                msg.obj = bitmap
                msg.what = GET_DATA_SUCCESS;
                callBackHandler.sendMessage(msg)
                Log.i("CustomImageView","cached 1!")
                return
            }
            AppExecutors.startTask( Thread {
                try {
                    val url = URL(path)
                    val connection =  url.openConnection() as HttpURLConnection
                    //使用GET方法访问网络
                    connection.requestMethod = "GET"
                    //超时时间为10
                    connection.connectTimeout = 10000
                    //获取返回码
                    var code = connection.responseCode
                    val inputStream = connection.inputStream
                    if (code == 200) {
                        //使用工厂把网络的输入流生产Bitmap
                        val bitmap = BitmapFactory.decodeStream(inputStream)
                        //利用Message把图片发给Handler
                        val msg = Message.obtain()

                        val value= SoftReference(bitmap)
                        ClientInfoHolder.map[path] = value
                        Log.i("CustomImageView","Mod:size:${ClientInfoHolder.map.size}")
                        msg.obj = bitmap
                        msg.what = GET_DATA_SUCCESS;
                        callBackHandler.sendMessage(msg)
                        Log.i("CustomImageView","apply from network")
                    }else {
                        //服务启发生错误
                        callBackHandler.sendEmptyMessage(SERVER_ERROR)
                        Log.i("CustomImageView","apply error")
                    }
                    inputStream.close()
                }catch (e:Exception){
                    e.printStackTrace()

                }
            })
            Log.i("CustomImageView","finish")
        }
    }


}